<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--企业数据-->
      <el-col :span="24" :xs="24">

        <basic-search-form ref="vBasicSearchForm" :columns="columns" inline size="small" @search="serach"  label-width="100px">

          <template #operateId="{ formdata }">
            <el-select v-model="formdata.operateId" placeholder="归属运营商" clearable style="width:100%" filterable>
              <el-option
                v-for="dict in operator"
                :key="dict.deptId"
                :label="dict.deptName"
                :value="dict.deptId"
              />
            </el-select>
          </template>
          
          <template #authStatus="{ formdata }">
            <el-select v-model="formdata.authStatus" placeholder="企业认证" clearable style="width:100%" >
              <el-option label="未认证" value="0" />
              <el-option label="已认证" value="1" />
              <el-option label="审核中" value="2" />
              <el-option label="认证失败" value="3" />
            </el-select>
          </template>

          <template #waterStatus="{ formdata }">
            <el-select v-model="formdata.waterStatus" placeholder="船运资质认证" clearable style="width:100%">
              <el-option label="未认证" value="0" />
              <el-option label="已认证" value="1" />
              <el-option label="审核中" value="2" />
              <el-option label="认证失败" value="3" />
            </el-select>
          </template>

          <template #status="{ formdata }">
            <el-select v-model="formdata.status" placeholder="企业状态" clearable style="width:100%">
              <el-option v-for="dict in dict.type.sys_state"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </template>
        </basic-search-form>

        <basic-table
          ref="vBasicTable"
          :api="getManageList"
          :immediate-fetch="false"
          :before-fetch="beforeFetch"
          :table-schema="tableSchema"
          :actions="tableActions"
          :table-prop="tableProp"
          :table-event="tableEvent"
          :row-info="{
            rowKey: 'data',
          }"
        >
          <template #companyNickName="{ row }">
            <div>{{ row.companyNickName }}</div>
            <div>{{ row.companyCode }}</div>
          </template>

          <template #userName="{ row }">
            <div style="display: flex; align-items: center">
              <div style="margin-right:10px;">
                <img style="width:30px;height:30px;border-radius:50%;" 
                    :src="row.avatar || require('@/assets/images/profile.jpg')" />
              </div>
              <div>
                <div>{{ row.userName }}</div>
                <div>{{ row.phonenumber }}</div>
              </div>
            </div>
          </template>

          <template #authStatusStr="{ row }">
            <div display="flex" align-items="center">
              <el-tag type="info" v-if="row.authStatus == 0">{{ row.authStatusStr }}</el-tag>
                <el-tag type="success" v-if="row.authStatus == 1">{{ row.authStatusStr }}</el-tag>
                <el-tag type="warning" v-if="row.authStatus == 2">{{ row.authStatusStr }}</el-tag>
                <el-tag type="danger" v-if="row.authStatus == 3">{{ row.authStatusStr }}</el-tag>
                <el-button size="mini" type="text" @click="handleAuth(row)" style="margin-left:10px;">
                  {{row.authStatus === 0 ? '发起认证' : '编辑认证'}}
                </el-button>
            </div>
          </template>
          
          <!-- 0-未认证,1-已认证,2-审核中,3-认证失败 -->
          <template #waterStatusStr="{ row }">
            <div display="flex" align-items="center">
              <div>
                <el-tag type="info" v-if="row.waterStatus == 0">{{ row.waterStatusStr }}</el-tag>
                <el-tag type="success" v-if="row.waterStatus == 1">{{ row.waterStatusStr }}</el-tag>
                <el-tag type="warning" v-if="row.waterStatus == 2">{{ row.waterStatusStr }}</el-tag>
                <el-tag type="danger" v-if="row.waterStatus == 3">{{ row.waterStatusStr }}</el-tag>
                <el-button size="mini" type="text" @click="handleWaterAuth(row)" style="margin-left:10px;">
                  {{row.authStatus === 0 ? '发起认证' : '编辑认证'}}
                </el-button>
              </div>
            </div>
          </template>

          <template #leader="{ row }">
            <div>{{ row.leader }}（{{ row.leaderPhone }}）</div>
          </template>

          <template #statusStr="{ row }">
            <div style="text-align:center">
              <el-tag type="info" v-if="row.status == 0">{{ row.statusStr }}</el-tag>
              <el-tag type="success" v-if="row.status == 1">{{ row.statusStr }}</el-tag>
            </div>
          </template>
          
          <!-- 表格上方按钮-->
          <template #tableHead="{ total }">
            <div>企业统计：{{ total }}</div>
            <div style="height: 32px">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">创建新企业</el-button>
              <el-button type="info" plain icon="el-icon-upload2" size="mini" :disabled="selecteds.length === 0" @click="handleBatchStatusChange(1)">批量禁用</el-button>
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="selecteds.length === 0" @click="handleBatchStatusChange(0)">批量恢复</el-button>
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
            </div>
          </template>
        </basic-table>

      </el-col>
    </el-row>

    <!-- 添加或修改企业配置对话框 -->
    <save-company-dialog
      :title="title"
      :currentId="form.id"
      :is-visible.sync="open"
      @dialogCallBack="handleDialogCallBack"
      ref="saveCompanyDialog"
    ></save-company-dialog>
    
  </div>
</template>

<script>
import { searchColumns, tableActions, tableSchema } from '@/views/enterprise/list/modal.data';
import saveCompanyDialog from '@/views/enterprise/list/components/SaveCompanyDialog.vue';
import {
  getManageList,
  getCompanyListByOperator,
  getOperateAndChannel,
  updateStatus,
  postCompanyManage,
  putCompanyManage,
} from '@/api/enterprise/index';
export default {
  name: 'CompanyList',
  dicts: ['sys_state', 'sys_user_sex', 'sys_auth_status'],
  components: { saveCompanyDialog },
  data() {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 企业表格数据
      manageList: null,
      // 弹出层标题
      title: '',
      // 企业下拉列表
      deptOptions: undefined,
      // 运营商下拉列表
      operator: null,
      // 是否显示弹出层
      open: false,
      selecteds: [],
      // 表单参数
      form: {
        id: null
      },
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      columns: searchColumns(this),
      tableSchema: tableSchema,
      tableActions: tableActions(this.handleUpdate, this.handleStatusChange, this.handleShowDetail),
      tableProp: {},
      tableEvent: {
        'selection-change': (selection) => {
          this.selecteds = selection.map((item) => item.id);
        },
      },
      // 查询参数
      queryParams: {},
    };
  },
  mounted() {
    this.getCompanyList();
    this.getOperateAndList();
    this.$refs.vBasicSearchForm.search();
  },
  methods: {
    getManageList,
    putCompanyManage,
    postCompanyManage,
    serach(form) {
      this.queryParams = { ...form };
      this.$refs.vBasicTable.fetch();
    },
    beforeFetch(params) {
      let query = {
        ...this.queryParams,
        createBeginTime:
          (this.queryParams.date?.[0] && dayjs(this.queryParams.date[0]).format('YYYY-MM-DD')) ||
          null,
        createEndTime:
          (this.queryParams.date?.[0] && dayjs(this.queryParams.date[1]).format('YYYY-MM-DD')) ||
          null,
      };
      delete query.date;
      return query;
    },
    // 查询企业下拉
    getCompanyList() {
      getCompanyListByOperator().then((res) => {
        this.deptOptions = res.data;
      });
    },
    // 查询运营商下拉
    getOperateAndList() {
      getOperateAndChannel().then((res) => {
        this.operator = res.data.operateList;
      });
    },
    handleDialogCallBack() {
      console.log('callback');
      this.open = false;
      this.$refs.vBasicSearchForm.search();
    },
    // 展示详情
    handleShowDetail(row) {
      this.form.id = row.id;
      this.$router.push({ name: 'CompanyDetail', query: { id: row.id } });
    },
    // 认证企业
    handleAuth(row) {
      this.$router.push({ name: 'CompanyAuth', query: { id: row.id } });
    },
    // 认证企业船舶资质
    handleWaterAuth(row) {
      this.$router.push({ name: 'CompanyWaterAuth', query: { id: row.id } });
    },
    // 添加企业
    handleAdd() {
      this.open = true;
      this.title = '创建企业';
    },
    // 编辑企业
    handleUpdate(row) {
      this.title = '编辑企业';
      this.form = { ...row };
      this.form.companyAdminPhone = { ...row }.phonenumber;
      this.form.citycopy = { ...row }.city;
      this.open = true;
    },
    // 企业状态修改
    handleStatusChange(row) {
      let text = row.status === 0 ? '恢复' : '禁用';
      this.$modal
        .confirm(`确认要${text}${row.companyNickName}吗？`)
        .then(() => {
          return updateStatus([row.id], row.status === 0 ? 1 : 0).then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess(text + '成功');
              this.$refs.vBasicSearchForm.search();
            }
          });
        })
        .catch(() => {});
    },
    // 批量修改禁用恢复
    handleBatchStatusChange(status) {
      console.log(this.selecteds);
      let text = status === 0 ? '批量恢复' : '批量禁用';
      this.$modal
        .confirm(`确认要${text}吗？`)
        .then(() => {
          updateStatus(this.selecteds, status === 0 ? 1 : 0).then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess(text + '成功');
              this.$refs.vBasicSearchForm.search();
            }
          });
        })
        .catch(() => {});
    },
    // 导出按钮操作
    handleExport() {
      this.download('/company/manage/export',{ ...this.queryParams, }, `企业列表_${new Date().getTime()}.xlsx` );
    },
  },
};
</script>
<style lang="scss" scoped>
.danger {
  color: #f56c6c;
}

.warning {
  color: #e6a23c;
}
</style>
